package group.rober.webruntime.interceptor;

import group.rober.runtime.holder.DateHolder;
import group.rober.runtime.holder.WebHolder;
import group.rober.runtime.kit.StringKit;
import group.rober.webruntime.core.WebRuntime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Web资源注入
 */
public class WebHolderInterceptor implements HandlerInterceptor {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestId = StringKit.uuid();
        HttpSession session = request.getSession(false);

        WebHolder.setRequest(request);
        WebHolder.setResponse(response);
        WebHolder.setSession(session);

        //设置请求一级的全局属性
        request.setAttribute(WebRuntime.KEY_REQUEST, requestId);
        MDC.put(WebRuntime.KEY_REQUEST,requestId);
        if(session != null){
            request.setAttribute(WebRuntime.KEY_SESSION, session.getId());
            MDC.put(WebRuntime.KEY_SESSION,session.getId());
        }

        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        WebHolder.clear();
        MDC.clear();
    }
}
